var router = require('koa-router')();


const host = 'api.yinuochoukuan.com';
const appid = 'wx771375a81245f6d4';
const appsecret = '525ebcfc354a942c275540941e013418';

//生成渠道专属二维码
router.post('/product/qrcodeStr' , async (ctx , next) => {
    let {id} = ctx.request.body;
    if(!id.startsWith("tel")){
        let introducer = await ctx.post('/admin/getIntroducerById',{id});
        if(introducer.cd == 0 && introducer.data.qrcode){
            ctx.body = {qrcodeStr:introducer.data.qrcode};
            return
        }
    }
    
    let result = await requestAccessToken(ctx);
    if(result.cd != 0){
        ctx.body = result;
        return;
    }
    let qrcodeStr = await ctx.superagent('post','https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+result.data,{
                "action_name": "QR_LIMIT_STR_SCENE", 
                "action_info": {
                    "scene": {
                        "scene_str": id
                    }
                }
            });
    qrcodeStr = JSON.parse(qrcodeStr);
    if(qrcodeStr.url && !id.startsWith("tel")){
        await ctx.post('/admin/updateQrcode',{id,QRcode:qrcodeStr.url});
    }
    ctx.body = {qrcodeStr:qrcodeStr.url} ;
})

//请求access_token
async function requestAccessToken(ctx){
    return await ctx.post('/admin/weixin/getAccessToken');
}

//
var qs = require('qs');
import https from "https";
import http from "http";
router.get('/h5/oauth', async(ctx, next) => {
    // let redirect_uri = ctx.protocol+`://${ctx.host}/weixin/oauth2`;
    // if(process.env.NODE_ENV=="dev"){
    let   redirect_uri = ctx.protocol+`://${host}/weixin/oauth2`;
    // }
    let weixin_url = `https://open.weixin.qq.com/connect/oauth2/authorize?${qs.stringify({appid, redirect_uri,response_type:'code', scope:'snsapi_base',state:"" })}#wechat_redirect`;
    ctx.redirect(weixin_url);
});


router.get('/oauth2', async(ctx, next) => {
        var {
            code,
        } = ctx.request.query;
        if (code) {
            var url =`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`
            var res = await await httpGet(url);
            var {access_token,openid = "123"} = JSON.parse(res);
            var result = await ctx.post('/admin/getIntroPhoneByOpenId' , {openid:openId});
            await ctx.redirect(`http://m.yinuochoukuan.com/register?beInviteCode=${result.data}`);
        } else {
            ctx.body = 'error: no code ';
        }
    });

    function httpGet(url){
        let protocol = url.startsWith('https')?https:http;
        return new Promise((resolve, reject)=>{
            protocol.get(url,(res) =>{
                res.on('data', (d) => {
                    resolve(d.toString());
                });
                 
            }).on('error', (e) => {
              console.error(e);
            });
    
        })
    }

export default router;
